<script> export default { name: 'crm:user' } </script>
<template>
  <el-container>

        <el-aside width="180px" style="border-right: 1px solid #e6e6e6; padding:10px;">
			<el-menu @select="handleTabsClick" :default-active="default_crm_sales_stag">
				<el-menu-item v-for="item in dictData.crm_sales_stag" :key="item.value" :index="item.value">
					<template #title>{{ item.label }}</template>
				</el-menu-item>
			</el-menu>
		</el-aside>

   <el-container ref="printMain">
    <el-header class="mine-el-header">
      <div class="panel-container">
        <!--列表操作-->
        <div class="left-panel">
          <el-button
            icon="el-icon-plus"
            v-auth="['crm:user:save']"
            type="primary"
            @click="add"
          >新增</el-button>

          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            v-auth="['crm:user:delete']"
            :disabled="selection.length==0"
            @click="batchDel"
          >删除</el-button>

          <ma-import
            :auth="['crm:user:import']"
            :upload-api="crmUser.importExcel"
            :download-tpl-api="crmUser.downloadTemplate"
            @success="handleSuccess()"
          />

          <el-button icon="el-icon-download" v-auth="['crm:user:export']" @click="exportExcel">导出</el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">

            <el-select v-model="queryParams.sales_stag" placeholder="请选择销售阶段" clearable>
              <el-option
                v-for='(item, index) in dictData.crm_sales_stag'
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button type="primary" icon="el-icon-search" @click="handlerSearch"></el-button>
            </el-tooltip>

            <el-tooltip class="item" effect="dark" content="清空条件" placement="top">
              <el-button icon="el-icon-refresh" @click="resetSearch"></el-button>
            </el-tooltip>

            <el-button type="text" @click="toggleFilterPanel">
              {{ povpoerShow ? '关闭更多筛选' : '显示更多筛选'}}
              <el-icon><el-icon-arrow-down v-if="povpoerShow" /><el-icon-arrow-up v-else /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      <!--列表筛选-->
      <el-card class="filter-panel" shadow="never">
        <el-form label-width="80px" :inline="true">

          <el-form-item label="跟进人" prop="follow_user_name">
            <el-input v-model="queryParams.follow_user_name" placeholder="请输入跟进人" clearable />
          </el-form-item>

          <el-form-item label="客户名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入客户名称" clearable />
          </el-form-item>

          <el-form-item label="客户来源" prop="from">
            <el-select v-model="queryParams.from" placeholder="请选择客户来源" clearable>
              <el-option
                v-for='(item, index) in dictData.crm_user_from'
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="需求级别" prop="level">
            <el-select v-model="queryParams.level" placeholder="请选择需求级别" clearable>
              <el-option
                v-for='(item, index) in dictData.crm_user_level'
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="电话" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入电话" clearable />
          </el-form-item>

          <el-form-item label="法人" prop="legal_perso">
            <el-input v-model="queryParams.legal_perso" placeholder="请输入法人" clearable />
          </el-form-item>

          <el-form-item label="姓名" prop="user_name">
            <el-input v-model="queryParams.user_name" placeholder="请输入姓名" clearable />
          </el-form-item>

          <el-form-item label="手机" prop="user_phone">
            <el-input v-model="queryParams.user_phone" placeholder="请输入手机" clearable />
          </el-form-item>

          <el-form-item label="微信" prop="user_wechat">
            <el-input v-model="queryParams.user_wechat" placeholder="请输入微信" clearable />
          </el-form-item>

          <el-form-item label="QQ" prop="user_qq">
            <el-input v-model="queryParams.user_qq" placeholder="请输入QQ" clearable />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            	<el-option
            		v-for='(item, index) in dictData.platform_data_status'
            		:key="index"
            		:label="item.label"
            		:value="item.value"
            	/>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间" prop="created_at">
            <el-date-picker
              v-model="queryParams.created_at" placeholder="请选择创建时间时间"
              type="datetimerange"  start-placeholder="起始时间" end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

        </el-form>
      </el-card>
    </el-header>
    <!--表格列表-->
    <el-main class="nopadding">
      <maTable
        ref="table"
        :api="api"
        :showRecycle="true"
        row-key="id"
        :hidePagination="false"
        @selection-change="selectionChange"
        @switch-data="switchData"
        stripe
        remoteSort
        @row-contextmenu="rowContextmenu"
      >
        <el-table-column type="selection" width="50"></el-table-column>

				<el-table-column label="客户名称" prop="name"  />

				<el-table-column label="销售阶段" prop="sales_stag" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.crm_sales_stag" :value="scope.row.sales_stag" />
            </template>
          </el-table-column>

          <el-table-column label="跟进人" prop="follow_user_name"  />


          <el-table-column label="客户来源" prop="from" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.crm_user_from" :value="scope.row.from" />
            </template>
          </el-table-column>

          <el-table-column label="需求级别" prop="level" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.crm_user_level" :value="scope.row.level" />
            </template>
          </el-table-column>

          <el-table-column label="官网" prop="com"  />

          <el-table-column label="电话" prop="phone"  />

          <el-table-column label="邮箱" prop="email"  />

          <el-table-column label="法人" prop="legal_perso"  />

          <el-table-column label="注册资本" prop="money"  />

          <el-table-column label="公司类型" prop="type"  />

          <el-table-column label="公司规模" prop="scale" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.crm_scale" :value="scope.row.scale" />
            </template>
          </el-table-column>

          <el-table-column label="所属行业" prop="industry"  />

          <el-table-column label="经营范围" prop="range"  />

<!--          <el-table-column label="地址" prop="address"  />-->

          <el-table-column label="详细地址" prop="address_detail"  />

          <el-table-column label="开户银行" prop="bank"  />

          <el-table-column label="银行账号" prop="bank_number"  />

          <el-table-column label="姓名" prop="user_name"  />

          <el-table-column label="性别" prop="sex" >
            <template #default="scope">
              <ma-dict-tag :options="dictData.sex" :value="scope.row.sex" />
            </template>
          </el-table-column>

          <el-table-column label="职位" prop="position"  />

          <el-table-column label="手机" prop="user_phone"  />

          <el-table-column label="邮箱" prop="user_email"  />

          <el-table-column label="微信" prop="user_wechat"  />

          <el-table-column label="钉钉" prop="user_ding"  />

          <el-table-column label="QQ" prop="user_qq"  />

          <el-table-column label="状态" prop="status" >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="proxy.$CONFIG.SWITCH.ENABLE"
                :inactive-value="proxy.$CONFIG.SWITCH.DISABLE"
                @change="updateSingle(scope.row.id,'status',scope.row.status)"
              />
            </template>
          </el-table-column>

          <el-table-column label="排序" prop="sort"  />

          <el-table-column label="创建时间" prop="created_at" width="100"  />

        <!-- 正常数据操作按钮 -->
        <el-table-column label="操作" fixed="right" align="right" width="130" v-if="!isRecycle">
          <template #default="scope">

            <el-button
              type="text"
              @click="tableEdit(scope.row, scope.$index)"
              v-auth="['crm:user:update']"
            >编辑</el-button>

            <el-button
              type="text"
              @click="deletes(scope.row.id)"
              v-auth="['crm:user:delete']"
            >删除</el-button>

          </template>
        </el-table-column>

        <!-- 回收站操作按钮 -->
        <el-table-column label="操作" fixed="right" align="right" width="130" v-else>
          <template #default="scope">

            <el-button
              type="text"
              v-auth="['crm:user:recovery']"
              @click="recovery(scope.row.id)"
            >恢复</el-button>

            <el-button
              type="text"
              v-auth="['crm:user:realDelete']"
              @click="deletes(scope.row.id)"
            >删除</el-button>

          </template>
        </el-table-column>

      </maTable>
    </el-main>

    <sc-contextmenu ref="contextmenu"  @command="handleCommand" @visible-change="visibleChange">
    	<sc-contextmenu-item command="edit" title="编辑"  suffix="Alt+←" icon="el-icon-edit"></sc-contextmenu-item>
    	<sc-contextmenu-item command="delete" title="删除" suffix="Ctrl+R" icon="el-icon-delete"></sc-contextmenu-item>
    </sc-contextmenu>

   </el-container>
  </el-container>

  <!--操作页面-->
  <save-dialog v-if="dialog.save" ref="saveRef" @success="handleSuccess" @closed="dialog.save=false" />

</template>
<script setup>
  import { ref, reactive, onMounted, nextTick,getCurrentInstance } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import crmUser from '@/api/apis/crm/crmUser'
  import tool from '@/utils/tool'
  import systemDict from '@/api/apis/system/dataDict'
  import scContextmenu from '@/components/scContextmenu'
  import scContextmenuItem from '@/components/scContextmenu/item'
  import saveDialog from './save.vue'

  const router = useRouter();
  const { proxy } = getCurrentInstance();
  const table = ref(null)
  const saveRef = ref(null)
  const povpoerShow = ref(false)
  const isRecycle = ref(false)
  const dateRange = ref()
  const selection = ref([])
  const default_crm_sales_stag = ref('-1')
  const contextmenu = ref(null)
  const rowdata = reactive({row:{}})

  const dialog = reactive({ save: false })
  const api = reactive({ list: crmUser.getList, recycleList: crmUser.getRecycleList })
  const queryParams = reactive({
    sales_stag: '',
    follow_user: '12761787285664',
		follow_user_name: '',
    name: '',
    from: '',
    level: '',
    phone: '',
    legal_perso: '',
    user_name: '',
    user_phone: '',
    user_wechat: '',
    user_qq: '',
    status: '',
    created_at: '',

  })
  const dictData = reactive({
    crm_sales_stag: [],
    crm_user_from: [],
    crm_user_level: [],
    crm_scale: [],
    sex: [],
    platform_data_status: [],

  })

  onMounted(async () => {
    await getDictData()
  })

  //添加
  const add = async () => {
    dialog.save = true
    await nextTick()
    saveRef.value.open()
  }

   // 标签页查询
    const handleTabsClick = (name) => {
        queryParams.sales_stag = name
	handlerSearch()
    }

  //编辑
  const tableEdit = async (row) => {
    dialog.save = true
    await nextTick()
    saveRef.value.open('edit')
    saveRef.value.setData(row)
  }

  //查看
  const tableShow = async (row) => {
    dialog.save = true
    await nextTick()
    saveRef.value.open('show')
    saveRef.value.setData(row)
  }

  //批量删除
  const batchDel = async () =>{
    await ElMessageBox.confirm(`确定删除选中的 ${selection.value.length} 项吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(async () => {
      let ids = []
      selection.value.map(item => ids.push(item.id))
      let res = isRecycle.value ? await crmUser.realDeletes(ids.join(',')) : await crmUser.deletes(ids.join(','))
      table.value.upData(queryParams)
      ElMessage.success(res.message)
    }).catch(()=>{})
  }

  // 单个删除
  const deletes = async (id) => {
    await ElMessageBox.confirm(`确定删除该数据吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(async () => {
      let res = isRecycle.value ? await crmUser.realDeletes(id) : await crmUser.deletes(id)
      table.value.upData(queryParams)
      ElMessage.success(res.message)
    }).catch(()=>{})
  }

  // 恢复数据
  const recovery = (id) => {
    crmUser.recoverys(id).then(res => {
      ElMessage.success(res.message)
      table.value.upData(queryParams)
    })
  }

  // 右键菜单
  const rowContextmenu = (row,column,event) => {

  	rowdata.row = row
  	table.value.setCurrentRow(row);
  	contextmenu.value.openMenu(event)
  }

  const handleCommand = (command) => {
  	if (command == 'edit') {
  		tableEdit(rowdata.row)
  	}
  	if (command == 'delete') {
  		deletes(rowdata.row.id)
  	}
  }

  const visibleChange = (visible) => {
  	if (!visible) {
  	}
  }

  //表格选择后回调事件
  const selectionChange = (items) => {
    selection.value = items
  }

  const toggleFilterPanel = () => {
    povpoerShow.value = ! povpoerShow.value
    document.querySelector('.filter-panel').style.display = povpoerShow.value ? 'block' : 'none'
  }

  //搜索
  const handlerSearch = () => {
    table.value.upData(queryParams)
  }

  // 切换数据类型回调
  const switchData = () => {
    isRecycle.value = ! isRecycle.value
  }

  // 重置搜索
  const resetSearch = () => {
    for (let k in queryParams) {
                 if (k == 'crm_sales_stag') {
               continue
         }
        queryParams[k] = undefined
    }
    table.value.upData(queryParams)
  }

  // 更新
  const handleSuccess = () =>{
    table.value.upData(queryParams)
  }

  // 获取字典数据
  const getDictData = () => {
    systemDict.getDict('crm_sales_stag').then(res => {
      dictData.crm_sales_stag = res.data
    })
    systemDict.getDict('crm_user_from').then(res => {
      dictData.crm_user_from = res.data
    })
    systemDict.getDict('crm_user_level').then(res => {
      dictData.crm_user_level = res.data
    })
    systemDict.getDict('crm_scale').then(res => {
      dictData.crm_scale = res.data
    })
    systemDict.getDict('sex').then(res => {
      dictData.sex = res.data
    })
    systemDict.getDict('platform_data_status').then(res => {
      dictData.platform_data_status = res.data
    })

  }

  // 修改单个数据
  	 const updateSingle = (id, editField,editValue) => {
       	let data = {[editField]: editValue};
       	crmUser.updateSingle(id, data).then(() => {
       		ElMessage.success('修改成功')
       	})
       }


  const exportExcel = () => {
    ElMessage.info('正在处理数据...')
    crmUser.exportExcel(queryParams).then( res => {
      tool.download(res)
    }).catch( e => { console.log(e) } )
  }

  const numberOperation = (newValue, id, numberName) => {
    crmUser.numberOperation({ id, numberName, numberValue: newValue }).then( res => {
      res.success && ElMessage.success(res.message)
    }).catch( e => { console.log(e) } )
  }

  const switchStatus = (statusValue, id, statusName) => {
    crmUser.changeStatus({ id, statusName, statusValue }).then( res => {
      res.success && ElMessage.success(res.message)
    }).catch( e => { console.log(e) } )
  }

</script>
